package com.ruoyi.tranShort.service.impl;

import java.util.List;

import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.mqtt.api.MqttClientApi;
import com.ruoyi.mqtt.impl.receive.ReceiveMessageCallback;
import com.ruoyi.tranShort.domain.ShortBaseStationDervice;
import com.ruoyi.tranShort.mapper.ShortBaseStationDerviceMapper;
import com.ruoyi.tranShort.mqtt.Subscribe;
import com.ruoyi.tranShort.mqtt.api.WristletWriteBackCallBack;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ruoyi.tranShort.mapper.ShortMqttConfigMapper;
import com.ruoyi.tranShort.domain.ShortMqttConfig;
import com.ruoyi.tranShort.service.IShortMqttConfigService;

/**
 * mqtt配置Service业务层处理
 * 
 * @author ruoyi
 * @date 2021-08-09
 */
@Service
public class ShortMqttConfigServiceImpl implements IShortMqttConfigService 
{
    private static final Logger LOGGER = LoggerFactory.getLogger(ShortMqttConfigServiceImpl.class);
    @Autowired
    private ShortMqttConfigMapper shortMqttConfigMapper;
    @Autowired
    private ShortBaseStationDerviceMapper shortBaseStationDerviceMapper;
    @Autowired
    private WristletWriteBackCallBack wristletWriteBackCallBack;
    public static MqttClientApi mqttClientApi;


    /**
     * mqtt主题模板
     */
    @Value("${mqtt.subscribeTopicTemplate}")
    private String topicTemplate;


    /**
     * 修改mqtt配置
     * 
     * @param shortMqttConfig mqtt配置
     * @return 结果
     */
    @Override
    public int updateShortMqttConfig(ShortMqttConfig shortMqttConfig)
    {
        LOGGER.info("========================mqtt连接开始==========================");
        int i = shortMqttConfigMapper.updateShortMqttConfig(shortMqttConfig);
        int connect = this.connect(shortMqttConfig);
        if(connect == 1){
            //连接成功，进行订阅主题
            //查询出所有主题
            List<ShortBaseStationDervice> shortBaseStationDerviceList = shortBaseStationDerviceMapper.selectShortBaseStationDerviceList(new ShortBaseStationDervice());
            for (ShortBaseStationDervice shortBaseStationDervice : shortBaseStationDerviceList) {
                String topic = topicTemplate.replace("#mac#", shortBaseStationDervice.getMac());
                mqttClientApi.subTopic(topic);
            }

            //设置叫哨回复回调
            Subscribe.wristletWriteBackCallBack = wristletWriteBackCallBack;
            LOGGER.info("========================mqtt连接成功==========================");
        }else{
            LOGGER.info("========================mqtt连接失败==========================");
        }
        return connect;
    }


    /**
     * 查询单个配置信息
     * @return
     */
    @Override
    public ShortMqttConfig selectShortMqttConfig() {
        return shortMqttConfigMapper.selectShortMqttConfig();
    }

    /**
     * 连接测试
     * @param shortMqttConfig
     * @return
     */
    @Override
    public int connectTest(ShortMqttConfig shortMqttConfig) {
        String ip = shortMqttConfig.getIp();
        Long port = shortMqttConfig.getPort();
        String username = shortMqttConfig.getUsername();
        String password = shortMqttConfig.getPassword();
        if(StringUtils.isEmpty(ip) || StringUtils.isEmpty(username) || StringUtils.isEmpty(password) || port == null){
            throw new CustomException("参数错误", HttpStatus.BAD_REQUEST);
        }
        StringBuilder tcpURIBuilder = new StringBuilder();
        tcpURIBuilder.append("tcp://").append(ip).append(":").append(port);
        MqttClientApi mqttClientApi = new MqttClientApi(tcpURIBuilder.toString(), UUID.randomUUID().toString(),username,password,new ReceiveMessageCallback());

        if(MqttClientApi.mqttClient != null){
            if(MqttClientApi.mqttClient.isConnected()){
                //连接成功
                //关闭连接
                mqttClientApi.closeConnect();
                return 1;
            }
        }
        return 0;
    }

    /**
     * 连接
     * @param shortMqttConfig
     * @return
     */
    @Override
    public int connect(ShortMqttConfig shortMqttConfig) {
        //判断是否连接，连接要先断开
        if(MqttClientApi.mqttClient != null){
            if(MqttClientApi.mqttClient.isConnected()){
                //已存在，进行断开连接
                mqttClientApi.closeConnect();
            }
        }
        String ip = shortMqttConfig.getIp();
        Long port = shortMqttConfig.getPort();
        String username = shortMqttConfig.getUsername();
        String password = shortMqttConfig.getPassword();
        if(StringUtils.isEmpty(ip) || StringUtils.isEmpty(username) || StringUtils.isEmpty(password) || port == null){
            throw new CustomException("参数错误", HttpStatus.BAD_REQUEST);
        }
        StringBuilder tcpURIBuilder = new StringBuilder();
        tcpURIBuilder.append("tcp://").append(ip).append(":").append(port);
        mqttClientApi = new MqttClientApi(tcpURIBuilder.toString(), UUID.randomUUID().toString(),username,password,new Subscribe());

        if(MqttClientApi.mqttClient != null){
            if(MqttClientApi.mqttClient.isConnected()){
                //连接成功
                return 1;
            }
        }
        return 0;
    }


}
